package middleware

import (
	"fmt"
	"simple-crm/models"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// LoggerMiddleware 日志中间件
func LoggerMiddleware(db *gorm.DB) gin.HandlerFunc {
	return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// 记录操作日志到数据库
		go func() {
			// 获取用户ID
			userID := getUserIDFromContext(param.Keys)
			if userID > 0 {
				// 根据请求路径和方法确定操作类型
				action := getActionFromRequest(param.Method, param.Path)
				resource := getResourceFromPath(param.Path)
				
				if action != "" && resource != "" {
					details := fmt.Sprintf("%s %s - %d", param.Method, param.Path, param.StatusCode)
					models.CreateLog(db, userID, action, resource, nil, details, param.ClientIP, "")
				}
			}
		}()

		// 返回日志格式
		return fmt.Sprintf("[%s] %s %s %d %s %s\n",
			param.TimeStamp.Format(time.RFC3339),
			param.Method,
			param.Path,
			param.StatusCode,
			param.Latency,
			param.ClientIP,
		)
	})
}

// getUserIDFromContext 从上下文获取用户ID
func getUserIDFromContext(keys map[string]interface{}) uint {
	if keys == nil {
		return 0
	}
	if userID, exists := keys["user_id"]; exists {
		if id, ok := userID.(uint); ok {
			return id
		}
	}
	return 0
}

// getActionFromRequest 根据请求方法和路径获取操作类型
func getActionFromRequest(method, path string) string {
	switch method {
	case "GET":
		return "view"
	case "POST":
		return "create"
	case "PUT", "PATCH":
		return "update"
	case "DELETE":
		return "delete"
	default:
		return ""
	}
}

// getResourceFromPath 根据路径获取资源类型
func getResourceFromPath(path string) string {
	if strings.Contains(path, "/users") {
		return "user"
	}
	if strings.Contains(path, "/customers") {
		return "customer"
	}
	if strings.Contains(path, "/partners") {
		return "partner"
	}
	if strings.Contains(path, "/push") {
		return "push_record"
	}
	if strings.Contains(path, "/roles") {
		return "role"
	}
	if strings.Contains(path, "/permissions") {
		return "permission"
	}
	return "system"
}